package com.ly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.entity.*;
import com.ly.mapper.*;
import com.ly.pojo.dto.TeamDTO;
import com.ly.pojo.vo.TeamVO;
import com.ly.service.TeamService;
import com.ly.utils.PageData;
import com.ly.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : 黑渊白花
 * @ClassName TeamServiceImpl
 * @date : 2025/2/8 22:31
 * @Description
 */
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {
    @Autowired
    private TeamMapper teamMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private TeamTypeMapper teamTypeMapper;
    @Autowired
    private JoinTeamMapper joinTeamMapper;


    @Override
    public IPage<TeamVO> getAllPage(TeamDTO teamDTO) {
        Integer pageNum = teamDTO.getPageNum();
        Integer pageSize = teamDTO.getPageSize();
        String name = teamDTO.getName();
        Integer typeId = teamDTO.getTypeId();
        IPage<TeamVO> page = new Page<>(pageNum,pageSize);
        // IPage<Map<String, Object>> mapPage = new Page<>(pageNum, pageSize);
        IPage<TeamVO> allPage = teamMapper.getAllPage(page, name, typeId);
        // page.setRecords(belongPage);
        // page.setTotal(belongPage.size());
        return allPage;
    }

    @Override
    public IPage<TeamVO> getAuditPage(TeamDTO teamDTO) {
        Integer pageNum = teamDTO.getPageNum();
        Integer pageSize = teamDTO.getPageSize();
        String name = teamDTO.getName();
        Integer typeId = teamDTO.getTypeId();
        IPage<TeamVO> page = new Page<>(pageNum,pageSize);
        IPage<TeamVO> auditPage = teamMapper.getAuditPage(page, name, typeId);
        return auditPage;
    }

    @Override
    public PageData getPageTr(TeamDTO teamDTO) {
        LambdaQueryWrapper<Team> lqw = new LambdaQueryWrapper<>();
        User user = null;
        if(teamDTO.getUserId()!=null){
            user= userMapper.selectById(teamDTO.getUserId());
        }
        //如果是社长就只显示自己的社团
        if(user!=null&&user.getType().equals("1")){
            lqw.eq(Strings.isNotEmpty(user.getName()),Team::getManager,user.getName());
        }
        lqw.eq(Team::getStatus,1);
        //如果是其他就显示所有
        lqw.like(Strings.isNotEmpty(teamDTO.getName()),Team::getName,teamDTO.getName());
        if(teamDTO.getTypeId()!=null){
            lqw.eq(Team::getTypeId,teamDTO.getTypeId());
        }
        IPage page = new Page(teamDTO.getPageNum(),teamDTO.getPageSize());
        IPage page1 = teamMapper.selectPage(page, lqw);
        return parsePage(page1);
    }

    public PageData parsePage(IPage<Team> p) {
        List<Map<String, Object>> resl = new ArrayList<Map<String, Object>>();
        for (Team teams : p.getRecords()) {
            Map<String, Object> temp = new HashMap<String, Object>();
            temp.put("id", teams.getId());
            temp.put("name", teams.getName());
            Date createTime = teams.getCreateTime();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String strDate1 = sdf1.format(createTime);
            temp.put("createTime", strDate1);
            temp.put("number", teams.getNumber());
            temp.put("details", teams.getDetails());
            temp.put("teacher", teams.getTeacher());
            temp.put("image",teams.getImage());
            temp.put("manager", teams.getManager());
            TeamType teamType = teamTypeMapper.selectById(teams.getTypeId());
            temp.put("typeId", teams.getTypeId());
            temp.put("typeName", teamType.getName());
            resl.add(temp);
        }
        PageData pageData = new PageData(p.getCurrent(), p.getSize(), p.getTotal(), resl);
        return pageData;
    }

    @Override
    public Boolean delete(Team team) {
        //第二种删除思路：有成员、其他数据就不删
        //要删除的话先让它把其他给删除完才能删
        QueryWrapper<JoinTeam> qw_joinTeam = new QueryWrapper();
        qw_joinTeam.eq("team_id", team.getId());
        Long count = joinTeamMapper.selectCount(qw_joinTeam);
        if(count>0){
            return false;
        }else {
            //删除的时候把社长变成成员,同时把成员表删除
            QueryWrapper qw=new QueryWrapper();
            qw.eq("name",team.getManager());
            User user = userMapper.selectOne(qw);
            user.setType("2");
            userMapper.updateById(user);
            teamMapper.deleteById(team.getId());
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("team_id", team.getId());
            memberMapper.delete(queryWrapper);
            return true;
        }
    }

    @Override
    public List<Map<String , Object>> getTeamAndEnterNum() {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name", "number").last("limit 8");
        List<Map<String , Object>> maps=teamMapper.selectMaps(queryWrapper);
        return maps;
    }

    @Override
    public List<Team> passList() {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",2);
        List<Team> teams = teamMapper.selectList(queryWrapper);
        return teams;
    }




    @Override
    public TeamVO getByManager(String name) {
        TeamVO byManager = teamMapper.getByManager(name);
        return byManager;
    }

    @Override
    public TeamVO getTeamById(Integer id) {
        TeamVO teamById = teamMapper.getTeamById(id);
        return teamById;
    }

    @Override
    public List<TeamVO> searchTByType(String typeName) {
        List<TeamVO> teamVOS = teamMapper.searchTByType(typeName);
        return teamVOS;
    }

    @Override
    public List<TeamVO> getTeamsByStuId(Integer stuId) {
        List<TeamVO> teamsByStuId = teamMapper.getTeamsByStuId(stuId);
        return teamsByStuId;
    }

    @Override
    public Result createTeam(TeamVO teamVO) {
        QueryWrapper<Member> qw = new QueryWrapper<>();
        qw.eq("stu_id",teamVO.getStuId());
        Long count = memberMapper.selectCount(qw);
        if(count >0){
            return Result.warn("还有加入的社团，请先退出社团");
        }
        QueryWrapper<Team> teamQWrapper = new QueryWrapper<>();
        teamQWrapper.eq("name",teamVO.getName());
        Team team = teamMapper.selectOne(teamQWrapper);
        if(team!=null){
            return Result.warn("该社团名已经存在，创建失败！");
        }
        Team addteam = new Team();
        BeanUtil.copyProperties(teamVO,addteam);
        teamMapper.insert(addteam);
        return Result.success("添加成功","申请社团成功，等待审核");
    }

    @Override
    public Result auditTeam(Team team) {
        //修改状态
        teamMapper.updateById(team);
        //如果拒绝不加入成员表，如果同意加入成员表,同时修改用户表将其变成社长
        if(team.getStatus()==1){
            return Result.success("审核成功","审核成功，拒绝创建");
        }
        if(team.getStatus()==2){
            QueryWrapper qw=new QueryWrapper();
            qw.eq("name",team.getManager());
            Student student = studentMapper.selectOne(qw);
            if(student==null){
                return Result.warn("该用户为找到，请检查数据库");
            }
            Member member = new Member();
            member.setStuId(student.getId());
            member.setTeamId(team.getId());
            memberMapper.insert(member);
            QueryWrapper qw1=new QueryWrapper();
            qw1.eq("name",team.getManager());
            User user = userMapper.selectOne(qw1);
            user.setType("1");
            userMapper.updateById(user);
            return Result.success("审核成功","审核成功，同意创建");
        }
        return Result.warn("创建失败");
    }

    @Override
    public Boolean deleteAll(Team team) {
        //第一种删除思路：要删除社团，要删除和社团有关的数据：
        //社团的新闻，预算，社团的成员，社团成员的申请记录，社团活动，社团成员申请加入活动记录
        //删除活动时，每个活动都有多个申请加入活动记录，所有要多次删除
        //最后删除社团，在判断该社团的团长是否还是其他社团的社长，如果不是则修改状态
        // QueryWrapper<News> qw_news = new QueryWrapper<News>();
        // qw_news.eq("team_id", team.getId());
        // newsMapper.delete(qw_news);
        //
        // QueryWrapper<Budget> qw_pay = new QueryWrapper<Budget>();
        // qw_pay.eq("team_id", team.getId());
        // budgetMapper.delete(qw_pay);
        //
        // QueryWrapper<JoinTeam> qw_JoinTeam = new QueryWrapper<JoinTeam>();
        // qw_JoinTeam.eq("team_id", team.getId());
        // joinTeamMapper.delete(qw_JoinTeam);
        //
        // QueryWrapper<Member> qw_member = new QueryWrapper<Member>();
        // qw_member.eq("team_id", team.getId());
        // memberMapper.delete(qw_member);
        // QueryWrapper<Activity> qw_active = new QueryWrapper<Activity>();
        // qw_active.eq("team_id", team.getId());
        // for(Activity activitie : activityMapper.selectList(qw_active)){
        //     QueryWrapper<JoinActivity> qw_JoinActivity = new QueryWrapper<JoinActivity>();
        //     qw_JoinActivity.eq("act_id", activitie.getId());
        //     joinActivityMapper.delete(qw_JoinActivity);
        // }
        // activityMapper.delete(qw_active);
        // teamMapper.deleteById(team);
        // QueryWrapper<Team> qw_team = new QueryWrapper<Team>();
        // qw_team.eq("manager", team.getManager());
        // if(teamMapper.selectCount(qw_team) <= 0){
        //     User user = userMapper.selectById(team.getManager());
        //     user.setType("2");
        //     userMapper.updateById(user);
        // }
        return false;
    }

}
